/*
Product : SN Editor, trình soan thao van ban  WYSIWYG cho cac ung dung web ;
Author : Sacroyant Nguyen ; Email : saroyant@gmail.com  ; Homepage : http://sacroyant.googlepages.com 

PAEditor (from QsvEditor)
	1. Add [View HTML] button 
	2. Add [Link] button
*/

var nav=navigator.appName;

var isIE=(nav.indexOf("Microsoft")>=0)?true:false;
var isMz=(nav=='Netscape')?true:false;
var isOp=(nav=='Opera')?true:false;


function PAEditor(instanceName, textarea, basepath){
	
    this.is=instanceName;
    this.textarea=textarea;
	this.basepath = basepath;
    
    this.ID=this.is+'_editor';
    this.UI=null;
    this.ed=null;
    this.sel=null;
	this.cache='';
    this.submenu=null;
    this.btnApp=null;
    this.preilta=null;
    this.ToolBar=textarea+'_toolBar';
    
    this.iconPath=basepath+'/icon/';
    this.textColor='#000000';
    this.textFont='sans-serif';
    this.textSize='14px';
    this.backgroundColor='#ffffff';
    this.toolbarColor="#f2fff2";
    this.showFootbar=false;
    this.viewSource=false;
   
    this.bs=[
        ['btnBold', 'Bold', 'bold.gif', this.is+'.format("bold")', 1],
        ['btnItalic', 'Italic', 'italic.gif', this.is+'.format("italic")', 1],
        ['btnUnderline', 'Underline', 'underline.gif', this.is+'.format("underline")', 1],
        ['btnFontface', 'Font Face', 'fontface.gif', this.is+'.fontface()', 1],
        ['btnFontsize', 'Font Size', 'fontsize.gif', this.is+'.fontsize()', 1],
        ['btnFontcolor', 'Font Color', 'fontcolor.gif', this.is+'.color(1)', 1],
        ['btnBackcolor', 'Background Color', 'bgcolor.gif', this.is+'.color(2)', 1],
        ['btnSuperscript', 'Super Script', 'sup.gif', this.is+'.format("superscript")', 1],
        ['btnSubscript', 'Sub Script', 'sub.gif', this.is+'.format("subscript")', 1],
        ['btnInsertLink', 'Insert Link', 'link.gif', this.is+'.addLink()', 1],
        ['btnInsertImage', 'Insert Image', 'image.gif', this.is+'.insertImage()', 1],
        ['btnAlignLeft', 'Align Left', 'alignLeft.gif', this.is+'.format("justifyleft")', 1],
        ['btnAlignCenter', 'Align Center', 'alignCenter.gif', this.is+'.format("justifycenter")', 1],
        ['btnAlignRight', 'Align Right', 'alignRight.gif', this.is+'.format("justifyright")', 1],
        ['btnAlignJustify', 'Align Justify', 'alignJustify.gif', this.is+'.format("justifyfull")', 1],
        ['btnOrderedList', 'Ordered List', 'orderedList.gif', this.is+'.format("insertorderedlist")', 1],
        ['btnBulletedList', 'Bulleted List', 'bulletedList.gif', this.is+'.format("insertunorderedlist")', 1],
        ['btnIndentMore', 'Indent', 'indent.gif', this.is+'.format("indent")', 1],
        ['btnOutdentMore', 'Outdent', 'outdent.gif', this.is+'.format("outdent")', 1],
        ['btnUnformat', 'Remove Formatting', 'removeformatting.gif', this.is+'.unformat()', 1],
        ['btnViewHtml', 'View HTML', 'html.gif', this.is+'.viewhtml()', 1]
    ];
    this.fontSize=[1,2,3,4,5,6,7];
    this.fontFace=['Courier','Georgia','Cursive','Fixedsys','Impact','Serif','Sans-Serif','Elephant'];
    this.colors=[
        ['#000000','Black'],
        ['#A0522D','Sienna'],
        ['#556B2F','Dark Olive Green'],
        ['#006400','Dark Green'],
        ['#483D8B','Dark Slate Blue'],
        ['#000080','Navy'],
        ['#4B0082','Indigo'],
        ['#2F4F4F','Dark Slate Gray'],
        ['#8B0000','Dark Red'],
        ['#FF8C00','Dark Orange'],
        ['#808000','Olive'],
        ['#008000','Green'],
        ['#008080','Teal'],
        ['#0000FF','Blue'],
        ['#708090','Slate Gray'],
        ['#696969','Dim Gray'],
        ['#FF0000','Red'],
        ['#F4A460','Sandy Brown'],
        ['#9ACD32','Yellow Green'],
        ['#2E8B57','Sea Green'],
        ['#48D1CC','Medium Turquoise'],
        ['#4169E1','RoyalBlue'],
        ['#800080','Purple'],
        ['#808080','Gray'],
        ['#FF00FF','Magenta'],
        ['#FFA500','Orange'],
        ['#FFFF00','Yellow'],
        ['#00FF00','Lime'],
        ['#00FFFF','Cyan'],
        ['#00BFFF','Deep SkyBlue'],
        ['#9932CC','Dark Orchid'],
        ['#C0C0C0','Silver'],
        ['#FFC0CB','Pink'],
        ['#F5DEB3','Wheat'],
        ['#FFFACD','Lemon Chiffon'],
        ['#98FB98','Pale Green'],
        ['#AFEEEE','Pale Turquoise'],
        ['#ADD8E6','Light Blue'],
        ['#DDA0DD','Plum'],
        ['#FFFFFF','White'],
        ['#DDA0DD','Plum'],
        ['#FFFFFF','White']
    ];
    this.controlButtons=[];

    this.sm=function(el,s){
        this.cm();
        this.rel(this.is+'_'+el).style.position='relative';
        var paf=document.createElement('div');
        var pop=document.createElement('div');
        var w=this.width;var h=this.height;
        paf.id=this.is+'_ePaf';
		pop.id=this.is+'_'+el+'_pop';
        
        with(paf.style){
            position='absolute';padding='0px';
            backgroundImage='url("'+this.iconPath+'bg.gif")';
            top=isOp?'35px':'28px';left='0px';zIndex='2';
            width=(w==0)?'100%':w+'px';height=(h-58)+'px';
        }
        
        with(pop.style){
            position='absolute';
            padding='2px';
            borderWidth='1px';
            borderStyle='solid';
            borderColor='#cccccc';
            background='#ffffff';
            cursor='default';
            top=isOp?'38px':'25px';
            left='0px';zIndex='3';
        }
        
        pop.innerHTML=s;
        this.rel(this.is+'_subMenu').appendChild(paf);
        this.rel(this.is+'_'+el+'_menu').appendChild(pop);
        this.sa(this.is+'_ePaf', 'click', this.is+'.cm()');
        this.submenu=this.is+'_'+el+'_pop';
        this.btnApp=this.is+'_'+el+'_menu';
        this.preilta=paf;
    }
    
    this.addButton=function(id,t,ic,f,no,i){
        if(i!=null&&!isNaN(i)&&i>=0&&i<this.bs.length){
            this.bs.splice(i,0,new Array(id,t,ic,f,(no==null)?1:no));
        }
        else{
            this.bs.push(new Array(id,t,ic,f,(no==null)?1:no));
        }
        
        this.ltb()
    }
    
    this.moveButton=function(id,ix,r){
        for(var i=0;i<this.bs.length;i++){
            if(id==this.bs[i][0]){
                if(r==2){
                    this.bs[i][4]=2
                }
                else{
                    this.bs[i][4]=1
                }
                if(!isNaN(ix)&&ix>=0&&ix<this.bs.length){
                    var t=this.bs[i];
                    this.bs.splice(i,1);
                    this.bs.splice(ix,0,t);
                };
                break;
            }
        }
        
        this.ltb();
    }
    
    this.cm=function(){
        if(this.submenu!=null){
            this.clearTxt(this.btnApp);
            this.submenu=null;
            if(this.preilta){
                this.rel(this.is+'_subMenu').removeChild(this.preilta);
                this.preilta=null;
            }
        }
    }
    
    this.unformat=function(){
        if(isOp){
            var sel=this.UI.getSelection();
            this.format('inserthtml',sel);
        }
        else{
            this.format('unlink');
            this.format('removeformat');
        }
    }
   
    this.getSelectedText=function(){
        if(!isIE){
            var sel=this.UI.getSelection();
            if(sel==''){
                return ''
            }
            var rg=sel.getRangeAt(0);
            var doc=rg.extractContents();
            var xmls=new XMLSerializer();
            return xmls.serializeToString(doc)
        }
        else{
			this.UI.focus();
            var ir=this.ed.selection.createRange();
            ir.select();
            return ir.htmlText;
        }
    }
    
    this.rel=function(ob){
        try{ 
            return document.getElementById(ob);
        }
        catch(e){}
    }
    
    this.gTxt=function(ob,txt){
        try{
            this.rel(ob).innerHTML=txt;
        }
        catch(e){}
    }
    
	
    this.clearTxt=function(ob){
        try{
            this.gTxt(ob,"");
        }
        catch(e){}
    }
    
    this.setStyle=function(ob,cln){
        this.rel(ob).className=cln;
    }
    
    this.color=function(no){
        var s='<div><table border="0" bgcolor="#999999" cellspacing="0" cellpadding="0">';
        var m=0;for(var i=0;i<5;i++){
            s+='<tr>';
            for(var j=0;j<8;j++){
                s+='<td title="'+this.colors[m][1]+'"><'+(isIE?'button':'div')+' id="bcm_'+m+'_'+no+'" class="cOut" onmouseover="'+this.is+'.setStyle(\'bcm_'+m+'_'+no+'\',\'cOver\');" onmouseout="'+this.is+'.setStyle(\'bcm_'+m+'_'+no+'\',\'cOut\');" style="background-color:'+this.colors[m][0]+';" onclick="'+this.is+'.format(\''+(no==1?'forecolor':(isIE?'backcolor':'hilitecolor'))+'\',\''+this.colors[m][0]+'\');'+this.is+'.cm();"> </'+(isIE?'button':'div')+'></td>';
                m++;
            }
            s+='</tr>';
        }
        s+='</table></div>';
        this.sm((no==1?'btnFontcolor':'btnBackcolor'),s);
    }
    
    this.fontsize=function(){
        var z=0,s='<table border="0" cellpadding="0" cellspacing="1" width="20">';
        for(var i=0;i<this.fontSize.length;i++){
            z=i+1;
            s+='<tr><td><'+(isIE?'button':'div')+' id="fsm'+i+'" class="mOut" style="border:none;font-family:serif;width:100%;text-align:center;margin:0px;padding:0px;"  onclick="'+this.is+'.format(\'fontsize\',\''+this.fontSize[i]+'\');'+this.is+'.cm();" onmouseover="'+this.is+'.setStyle(\'fsm'+i+'\',\'mOn\');" onmouseout="'+this.is+'.setStyle(\'fsm'+i+'\',\'mOut\');" title="'+z+'"><font size="'+this.fontSize[i]+'">'+this.fontSize[i]+'</font></'+(isIE?'button':'div')+'></td></tr>';
        }
        s+='</table>';
        this.sm('btnFontsize',s);
    }
    
    this.fontface=function(){
        var s='<table cellpadding="0" cellspacing="0" width="100">';
        for(var i=0;i<this.fontFace.length;i++){
            s+='<tr><td><'+(isIE?'button':'div')+' id="ffm'+i+'" class="mOut" style="border:none;font-family:serif;width:100%;text-align:left;margin:0px;padding:0px;" onclick="'+this.is+'.format(\'fontname\',\''+this.fontFace[i]+'\');'+this.is+'.cm();" onmouseover="'+this.is+'.setStyle(\'ffm'+i+'\',\'mOn\');" onmouseout="'+this.is+'.setStyle(\'ffm'+i+'\',\'mOut\');" title="'+this.fontFace[i]+'">   <font face="'+this.fontFace[i]+'">'+this.fontFace[i]+'</font></'+(isIE?'button':'div')+'></td></tr>';
        }
        s+='</table>';
        this.sm('btnFontface',s);
    }
    
    this.undoClear=function(){
        if(this.cache!=''){
            this.cnt=this.cache;
            this.ed.body.innerHTML=this.cnt;
            this.cache='';
            this.clearTxt('undo');
        }
    }
 
    this.clearAll=function(){
        this.cache=this.getHTML();
        this.cnt="";
        this.ed.body.innerHTML='<br>';
        if(this.cache.length>5){
            this.gTxt('undo','<span class="ctr" id="btnUndoClear" title="Undo Clear">Undo</span>');
            this.sa('btnUndoClear','click',this.is+'.undoClear();');
        }
    }
    
    this.selectAll=function(){
        this.cm();
        this.format('selectall');
        this.UI.focus();
    }
    
    this.getHTML=function(){
        return this.ed.body.innerHTML;
    }
    
    this.getContent=function(){
        return this.getHTML();
    }
    
    this.getText=function(){
        return isIE?this.ed.body.innerText:this.ed.body.textContent;
    }
	
	// Gan noi dung moi cho editor - boi Son PA (23-09-2010)
    this.setContent=function(cnt){
		this.ed.body.innerHTML = cnt;
		//alert(this.ed.body.innerHTML);
        return this;
    }
    

	
	// Them noi dung moi tai vi tri chuot - boi Son PA (23-09-2010)
	// Neu dang chon 1 doan text thi thay the luon
    this.insertContent=function(cnt){
		var ss=this.getSelectedText();
		var text = cnt;
		if(!isIE){
			this.format('inserthtml',text);
		}
		else{
			var ig=this.ed.selection.createRange();
			ig.select();
			ig.pasteHTML(text);
		}
        return this;
    }
	
    this.removeButton=function(btn){
        for(var k=0;k<arguments.length;k++){
            if(!isNaN(arguments[k])){
                if(arguments[k]>=0&&arguments[k]<this.bs.length){
                    this.bs.splice(arguments[k],1);
                }
            }
            else{
                for(var i=0;i<this.bs.length;i++){
                    if(arguments[k]==this.bs[i][0]){
                        this.bs.splice(i,1);
                        break;
                    }
                }
            }
        }
        this.ltb()
    }
    
    this.ltb=function(){
        var s='<table border="0" cellpadding="1" cellspacing="0">';
        var tt=1;
        for(var i=0;i<this.bs.length;i++){
            if(this.bs[i][4]!=1){
                tt=2;
                break;
            }
        }
        
        if(tt==1){
            s+='<tr height="25">';
            for(var i=0;i<this.bs.length;i++){
                s+='<td width="20">';
                s+='<span style="position:relative;" id="'+this.is+'_'+this.bs[i][0]+'_menu"></span><div id="'+this.is+'_'+this.bs[i][0]+'" style="background-image:url('+this.iconPath+this.bs[i][2]+');background-repeat:no-repeat;background-position: center center;" class="bOut" title="'+this.bs[i][1]+'"><img src="'+this.iconPath+'bg.gif" width="18" height="18"></div>';s+='</td>';
            }
            s+='</tr>';
        }
        else if(tt==2){
            s+='<tr height="20">';
            var mx=m=n=0;
            r=[[],[]];
            for(var i=0;i<this.bs.length;i++){
                if(this.bs[i][4]==1){
                    r[0].push(this.bs[i]);
                    m++;
                }
                else{
                    r[1].push(this.bs[i]);
                    n++;
                }
            }
            mx=m>n?m:n;
            for(var i=0;i<mx;i++){
                if(i<r[0].length){
                    s+='<td width="20">';
                    s+='<span style="position:relative;" id="'+this.is+'_'+r[0][i][0]+'_menu"></span><div id="'+this.is+'_'+r[0][i][0]+'" style="background-image:url('+this.iconPath+r[0][i][2]+');background-repeat:no-repeat;background-position: center center;" class="bOut" title="'+r[0][i][1]+'"><img src="'+this.iconPath+'bg.gif" width="18" height="18"></div>';
                    s+='</td>';
                }
                else{
                    s+='<td width="20">&nbsp;</td>';
                }
            }
            
            s+='</tr>';
            s+='<tr height="25">';
            for(var i=0;i<mx;i++){
                if(i<r[1].length){
                    s+='<td width="20">';
                    s+='<span style="position:relative;" id="'+this.is+'_'+r[1][i][0]+'_menu"></span><div id="'+this.is+'_'+r[1][i][0]+'" style="background-image:url('+this.iconPath+r[1][i][2]+');background-repeat:no-repeat;background-position: center center;" class="bOut" title="'+r[1][i][1]+'"><img src="'+this.iconPath+'bg.gif" width="18" height="18"></div>'
                    s+='</td>';
                }
                else{
                    s+='<td width="20">&nbsp;</td>';
                }
            }
            s+='</tr>';
        }
        
        s+='</table>';
        
        this.gTxt(this.ToolBar,s);
        for(var i=0;i<this.bs.length;i++){
            if(this.bs[i].callback!=''){
                this.sa(this.is+'_'+this.bs[i][0],'click',this.bs[i][3]);
            }
            this.sa(this.is+'_'+this.bs[i][0],'mouseout',this.is+'.setStyle("'+this.is+'_'+this.bs[i][0]+'","bOut")');
            this.sa(this.is+'_'+this.bs[i][0], 'mouseover', this.is+'.setStyle("'+this.is+'_'+this.bs[i][0]+'","bOver")');
        }
    }
    
    this.sa=function(o,e,f){
        var el=this.rel(o);
        if(el!=null){
            if(el.addEventListener){
                el.addEventListener(e,new Function(f),false)
            }
            else if(el.attachEvent){
                el.attachEvent('on'+e, new Function(f))
            }
        }
    }
    
	
    this.display=function(){
		var textarea = this.rel(this.textarea);

		// get the content of editor
    	this.cnt=textarea.value;
		this.width=textarea.style.width.replace(/[^0-9]/gi,"");
		this.height=textarea.style.height.replace(/[^0-9]/gi,"");
		textarea.style.display	= 'none';
		textarea.style.overflow = 'auto';
	
		
        var sEditor='<iframe id="'+this.ID+'" style="width:'+((this.width<101)?'99%':(this.width-5)+'px')+';height:'+(this.height-(this.showFootbar?55:30))+'px;overflow:auto;margin:0px;padding:0px;"></iframe>';      
        var sCB=''; 
        var s='<table border="0" width="'+((this.width<101)?'100%':this.width)+'" height="'+this.height+'" cellpadding="1" cellspacing="0" style="background-color:#f7fff3;"><tr height="25" bgcolor="'+this.toolbarColor+'"><td colspan="2"><span id="'+this.is+'_subMenu" style="position:relative;top:0px;left:0px;"></span><span id="'+this.ToolBar+'"> </span></td></tr><tr height="'+(this.height-(this.showFootbar?50:25))+'"><td colspan="2">'+sEditor+'</td></tr>';
        
        if(this.showFootbar){
            for(var i=0;i<this.controlButtons.length;i++){
                sCB+='<input type="button" name="'+this.is+'_'+this.controlButtons[i][0] +'" id="'+this.is+'_'+this.controlButtons[i][0]+'" value="'+this.controlButtons[i][1] +'" style="width:100px;" class="mouseOut" title="'+this.controlButtons[i][1]+'">';
            }
            s+='<tr height="25"><td colspan="2"><table border="0" width="100%" height="100%" cellpadding="0" cellspacing="0"><tr><td>  <span class="ctrE" title="Select All" onclick="'+this.is+'.selectAll();">Select All</span>   <span class="ctrE" title=" Clear All " onclick="'+this.is+'.clearAll();">Clear All</span>    <span id="undo" style="background-color:#ffff99;"></span></td><td align="right">'+sCB+'</td></tr></table></td></tr>';
        }
        
        s+='</table>';
		
 		// create a new SPAN element as a container for editor
        var edparent = textarea.parentNode;
       	var container = document.createElement("span");
		edparent.insertBefore(container,textarea);
		container.id = this.textarea + "_Editor";		
		container.innerHTML = s;

		// Tao nut view Editor - SonPA (30-03-2011)
		var btnEditor = document.createElement("span");
		edparent.insertBefore(btnEditor,textarea);
		btnEditor.id = this.textarea + "_Html";
		btnEditor.innerHTML = '<a href="#viewHtml" onclick="'+this.is+'.viewhtml();return false" style="display:block;background:#f7fff3;width:'+((this.width==0)?'100%':this.width+'px')+';height:25px;color:#00f;text-decoration:none;line-height:25px;text-align:center">Trở lại giao diện chỉnh sửa HTML</a>';
		btnEditor.style.display="none";

		//this.gTxt(this.textarea + "_Editor",s);
        this.ltb();
        if(this.showFootbar){
            for(var i=0;i<this.controlButtons.length;i++){
                var btnid=this.is+'_'+this.controlButtons[i][0];
                this.sa(btnid,'click', this.controlButtons[i][2]);
                this.sa(btnid,'mouseover',this.is+'.setStyle("'+btnid+'","mouseOn")');
                this.sa(btnid,'mouseout',this.is+'.setStyle("'+btnid+'","mouseOut")');
            }
        }
		
        this.UI=this.rel(this.ID).contentWindow;
        this.ed=this.UI.document;
        with(this.ed){
            designMode='On';
		    open();
			write('<html><head></head><body style="color:'+this.textColor+';font-family:'+this.textFont+';font-size:'+this.textSize+';margin:2px;padding:4px;background-color:'+this.backgroundColor+'">'+this.cnt+' </body></html>');
		
            close();
        }
		
        this.UI.focus();
		
		// Tu cap nhat lai noi dung textarea
		this.setTimer();
	
	},
	

	
	// View HTML - SonPA (30-03-2011)
	this.viewhtml = function(){
		var textarea	= this.rel(this.textarea);
		var editor		= this.rel(this.textarea+'_Editor');
		var btnEditor	= this.rel(this.textarea+'_Html');
		this.viewSource = !this.viewSource;
		
		if(this.viewSource){
			textarea.style.display='block';
			editor.style.display='none';
			btnEditor.style.display='block';
			
			// Xoa timer
			this.clearTimer();
		}
		else{
			textarea.style.display='none';
			editor.style.display='block';
			btnEditor.style.display='none';
			
			// Cap nhat lai noi dung cho Editor
			this.setContent(textarea.value);			
			// Tao lai Timer
			this.setTimer();
		}
		
	}
	
    this.format=function(c,v){
        this.cm();
        if(this.ed.queryCommandEnabled(c)){
            if(!v){
                v=null;
            }
            
            this.ed.execCommand(c,false,v);
            this.UI.focus();
        }
    }
    
	this.addLink=function(){
		if(isIE) this.sel = this.saveSelection();
		var s='<table border="0" cellpadding="0" cellspacing="0">';
        s+='<tr><td>Nhập đường dẫn:<br /><input type="text" id="imgLink" style="width:180px" /></td></tr><tr><td height="25" valign="bottom"><input type="button" value="Đồng ý" onclick="if('+this.is+'.rel(\'imgLink\').value!=\'\'){if(isIE)'+this.is+'.restoreSelection('+this.is+'.sel);'+this.is+'.format(\'CreateLink\','+this.is+'.rel(\'imgLink\').value);'+this.is+'.cm();}" style="height:20px;border:thin" /> <input type="button" value="Bỏ qua" onclick="'+this.is+'.cm()" style="height:20px;border:thin" /></td></tr>';
        s+='</table>';
        this.sm('btnInsertLink',s);
    }
    
    this.insertImage=function(){
		if(isIE) this.sel = this.saveSelection();
		var s='<table border="0" cellpadding="0" cellspacing="0">';
        s+='<tr><td>Nhập đường dẫn hình ảnh:<br /><input type="text" id="urlLink" style="width:180px" /></td></tr><tr><td height="25" valign="bottom"><input type="button" value="Đồng ý" onclick="if('+this.is+'.rel(\'urlLink\').value!=\'\'){if(isIE)'+this.is+'.restoreSelection('+this.is+'.sel);'+this.is+'.format(\'InsertImage\','+this.is+'.rel(\'urlLink\').value);'+this.is+'.cm();}" style="height:20px;border:thin" /> <input type="button" value="Bỏ qua" onclick="'+this.is+'.cm()" style="height:20px;border:thin" /></td></tr>';
        s+='</table>';
        this.sm('btnInsertImage',s);
    }

	this.saveSelection = function(){
		var ir=this.ed.selection.createRange();
		return ir;//.duplicate();	
	}
	
	this.restoreSelection = function(sel){
		this.UI.focus();
		sel.select();
	}
	
	this.setTimer = function(){
		var thised 		= this;
		var textarea	= this.rel(this.textarea);
		this.edTime = window.setInterval(function(){textarea.value = thised.getContent()},1);		
	}
	
	
	this.clearTimer = function(){
		clearTimeout(this.edTime);
		this.edTime = null;
	}
	
	this.destroy = function(){
		this.clearTimer();
		this.is = null
		this.textarea = null;
	}

	// Auto display editor
	this.display();
	
}